#

UserOperation = require("../models/user_op").UserOperation
log = require("../services/logging").log

parse_date = (x) ->
  m = /(\d\d\d\d)(\d\d)(\d\d)/.exec(x)
  if m
    year = m[1]
    month = Number(m[2])-1
    day = m[3]
    return new Date(year,month,day)

g_titles = []
exports.list_user_op_titles = (req,res) ->
  return res.json g_titles
          
exports.query_trade_user_op = (req,res) ->
  begin_date = parse_date(req.param("begin_date"))
  end_date = parse_date(req.param("end_date"))
  if end_date
    end_date = end_date.addDays(1)
  result = req.param("success")
  if result == "true"
    result = true
  else if result == "false"
    result = false
  else
    result = null
  title = req.param("title")
  page_num = Number(req.param("pageNum")) or 1
  page_size = Number(req.param("pageSize")) or 50

  id = req?.session?.user?.trade?.khbh
  UserOperation.search id,title,result,begin_date,end_date,page_num,page_size,(err,ops) ->
    if err
      return resErr res, err
    else
      return res.json ops
  

exports.record_trade_user_op_description = (req,desc) ->
  if req?.session?.user_op? and desc
    req.session.user_op.desc = desc


exports.record_trade_user_op = (title,desc) ->
  unless g_titles.indexOf(title) >= 0
    g_titles.push title
    
  (req,res,next) ->
    if req.method == "POST"  # 只有POST才能修改数据
      unless req.session.user_op
        req.session.user_op = {}
      delete req.session.user_op.desc
      req.session.user_op.record = true

      get_error_msg = (args) ->
        error = null
        for x in args
          if typeof(x) == "object" and (x?.error or x?.error_info)
            error = x.error or x.error_info
            break
          else if typeof(x) == "string" and x.indexOf("error") > 0
            try
              y = JSON.parse x
              if y?.error or y?.error_info
                error = y?.error or y?.error_info
                break
            catch error
        return error

      orig_send = res.send
      res.send = (args...) ->
        if req.session.user_op.record
          error = get_error_msg(args) or ""
          is_success = (@statusCode == 200 and not error)
          id = req.session?.user?.trade?.khbh
          desc = desc or req.session?.user_op?.desc or title
          if id
            log "gfportal", {type:"service_op", tradeid: id, title, desc, is_success, error, info:""}
            UserOperation.record_trade_user_op id,title,desc,is_success,error,->
          req.session.user_op.record = false
        orig_send.apply(this,args)
    next()
  
